package com.tadpole.music.utils.update;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;


import com.tadpole.music.R;
import com.tadpole.music.app.MyApplication;

import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.lzh.framework.updatepluginlib.base.CheckNotifier;
import org.lzh.framework.updatepluginlib.model.Update;
import org.lzh.framework.updatepluginlib.util.CleanUtil;

/**
 * 简单实现：使用通知对用户提示：检查到有更新
 */
public class NotificationUpdateCreatorMandatory extends CheckNotifier {
    private final static String ACTION_UPDATE = "action.update.shot";
    private final static String ACTION_CANCEL = "action.update.cancel";
    private RequestUpdateReceiver requestUpdateReceiver;
    private Update update;
    private UpdateBuilder builderWM;
    NotificationManager manager;
    NotificationUpdateCreatorI notificationUpdateCreatorI;
    int id;
    private String mCurVersionName;  //版本名称
    private int mCurVersionCode;     //版本号

    public NotificationUpdateCreatorMandatory(UpdateBuilder builderWM,
                                              String mCurVersionName,
                                              int mCurVersionCode,
                                              NotificationUpdateCreatorI notificationUpdateCreatorI) {
        this.builderWM = builderWM;
        this.notificationUpdateCreatorI = notificationUpdateCreatorI;
        this.mCurVersionName = mCurVersionName;
        this.mCurVersionCode = mCurVersionCode;
    }

    @Override
    public Dialog create(Activity context) {
        requestUpdateReceiver = new RequestUpdateReceiver();
        registerReceiver(context);
        createNotification(context);
        this.update = update;

        // 由于需要使用通知实现。此处返回null即可
        return null;
    }

    @SuppressLint("NewApi")
    private void createNotification(Context context) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.CustomDialogOne);
        final View dialogview = View.inflate(context, R.layout.pop_layout_update_version, null);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        dialogview.setMinimumWidth(width / 100 * 80);
        final TextView mContent = (TextView) dialogview.findViewById(R.id.tv_content);
        final Button mBtnUpdate = (Button) dialogview.findViewById(R.id.btn_update);
        mContent.setText(MyApplication.getInstance().update.getUpdateContent());
        // 设置提示框的标题
        builder.setView(dialogview);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();

        mBtnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationUpdateCreatorI.onClick(1);
                sendDownloadRequest();
                alertDialog.dismiss();
            }
        });

        if(mCurVersionCode<MyApplication.getInstance().update.getVersionCode()) {
            if (MyApplication.getInstance().update.isForced()) {
                try {
                    //清除缓存
                    CleanUtil.cleanApplicationData(MyApplication.getInstance());
                    SharedPreferences sp = context.getSharedPreferences("is_first", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("isFirstUse", false);
                    editor.commit();
                }catch (Exception e){
                    e.printStackTrace();
                }
                // 显示对话框
                alertDialog.show();
            } else {
                notificationUpdateCreatorI.isNotMandatory();
            }
        }else{
            notificationUpdateCreatorI.isNotMandatory();
        }
    }

    public class RequestUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent);
            unregisterReceiver(context);
            if (ACTION_UPDATE.equals(intent.getAction())) {
                // 发送下载请求。继续更新流程
                sendDownloadRequest();
            } else {
                // 中断更新流程并通知用户取消更新
                sendUserCancel();
            }
            manager.cancel(id);
        }
    }

    private void registerReceiver (Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_UPDATE);
        filter.addAction(ACTION_CANCEL);
        context.registerReceiver(requestUpdateReceiver, filter);
    }

    private void unregisterReceiver (Context context) {
        context.unregisterReceiver(requestUpdateReceiver);
    }


    public interface NotificationUpdateCreatorI{

        void onClick(int button);
        void isNotMandatory();


    }
}
